import Application from './Application'
import { ComponentInterface } from './Component'

export default class Screen {
  async resize() {
    await Promise.all(this.children.map(async (child) => {
      await child.resize()
    }))
  }
  application: Application
  children: ComponentInterface[]

  constructor(options: {
    children?: ComponentInterface[]
  }) {
    this.children = options.children || []
  }

  /**
   * 初始化
   */
  async init() {
    await Promise.all(this.children.map(async (child) => {
      child.screen = this
      await child.init()
    }))
  }
  /**
   * 加载
   */
  async load() {
    await Promise.all(this.children.map(async (child) => {
      await child.load()
    }))
  }

  /**
   * 卸载
   */
  async unload() {
    await Promise.all(this.children.map(async (child) => {
      await child.unload()
    }))
  }
  /**
   * 销毁
   */
  async destroy() {
    await Promise.all(this.children.map(async (child) => {
      await child.destroy()
    }))
    this.children = []
  }
  /**
   * 更新
   * @param dt 时间差
   */
  async update(dt: number) {
    await Promise.all(this.children.map(async (com) => {
      await com.update(dt)
    }))
  }

  /**
   * 添加组件
   * @param component 组件
   */
  async addComponent(component: ComponentInterface) {
    component.screen = this
    await component.init()
    await component.load()
  }
  /**
   * 移除组件
   * @param component 组件
   */
  async removeComponent(component: ComponentInterface) {
    await component.unload()
    await component.destroy()
  }
}